<template>
  <div class="container">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <div class="search-wrapper">
        <!-- 搜索表单 -->
        <div class="search-form-section">
          <el-form :inline="true" :model="queryParams" ref="queryForm" class="demo-form-inline">
            <el-form-item label="项目信息">
              <el-input
                :model-value="selectedProject ? selectedProject.name : ''"
                placeholder="请选择项目"
                readonly
                class="selector-input"
              >
                <template #append>
                  <el-button @click="openProjectSelector" v-permission="['budgetSheet:view']">选择</el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="客户名称">
              <el-select v-model="queryParams.customerId" placeholder="请选择客户" clearable filterable style="width: 200px">
                <el-option
                  v-for="item in customerOptions"
                  :key="item.id"
                  :label="item.companyName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="业务员">
              <el-select v-model="queryParams.personId" placeholder="请选择业务员" clearable filterable style="width: 160px">
                <el-option
                  v-for="item in personOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item class="search-buttons">
              <el-button type="primary" @click="handleQuery" class="search-btn" v-permission="['budgetSheet:view']">
                <el-icon><Search /></el-icon>
                查询
              </el-button>
              <el-button @click="resetQuery" class="reset-btn" v-permission="['budgetSheet:view']">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 操作按钮区域 -->
        <div class="action-buttons-section">
          <div class="button-group primary-actions">
            <!-- 主要操作按钮 -->
          </div>
          
          <div class="button-group secondary-actions">
            <el-button type="success" @click="handleAdd" class="add-btn" v-permission="['budgetSheet:edit']">
              <el-icon><Plus /></el-icon>
              新增
            </el-button>
          </div>

          <div class="button-group secondary-actions">
            <el-button type="success" @click="openProjectSelectorForReport" class="add-btn" v-permission="['budgetSheet:view']">
              <el-icon><Plus /></el-icon>
              预览产品预算明细成本报表
            </el-button>
          </div>

        </div>
      </div>
    </el-card>

    <!-- 数据列表 -->
    <el-card class="list-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="dataList"
        :height="tableHeight"
        element-loading-text="加载中..."
        element-loading-background="rgba(255, 255, 255, 0.7)"
        style="width: 100%"
        stripe
        border
      >
        <el-table-column type="index" width="60" label="序号" align="center" />
        <el-table-column prop="projectName" label="项目名称" min-width="150" align="center" show-overflow-tooltip />
        <el-table-column prop="customerName" label="客户名称" min-width="150" align="center" show-overflow-tooltip />
        <el-table-column prop="personName" label="业务员" min-width="120" align="center" show-overflow-tooltip />
        <el-table-column prop="targetAmount" label="目标金额(元)" min-width="120" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span class="price-value">{{ formatPrice(scope.row.targetAmount) }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="grossMargin" label="毛利率()" min-width="100" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ formatPercentage(scope.row.grossMargin) }}</span>
          </template>
        </el-table-column> -->
        <el-table-column prop="createTime" label="创建时间" min-width="180" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span class="date-value">{{ formatDate(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createName" label="创建人" min-width="120" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.createName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" min-width="180" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span class="date-value">{{ formatDate(scope.row.updateTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="updateName" label="更新人" min-width="120" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.updateName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleDetail(scope.row.id)" v-permission="['budgetSheet:view']">
              查看
            </el-button>
            <el-button type="primary" size="small" @click="handleEdit(scope.row.id)" v-permission="['budgetSheet:edit']">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row.id)" v-permission="['budgetSheet:edit']">
              删除
            </el-button>
            <el-button type="success" size="small" @click="handlePrint(scope.row)" v-permission="['budgetSheet:view']">
              生成预算单
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.limit"
          :page-sizes="[10, 20, 50, 100]"
          :background="true"
          layout="prev, pager, next, jumper,->,sizes,total"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- 项目选择器对话框 -->
    <ArchiveSelector
      v-model="projectSelectorVisible"
      title="选择项目"
      :search-fields="projectSearchFields"
      :table-columns="projectTableColumns"
      :fetch-data-api="getProjectList"
      :multiple="false"
      @confirm="handleProjectSelect"
    />
    
    <!-- 报表项目选择器对话框 -->
    <el-dialog
      v-model="reportProjectSelectorVisible"
      title="选择项目"
      width="800px"
      destroy-on-close
    >
      <div class="project-selector-container">
        <!-- 搜索区域 -->
        <div class="search-area">
          <el-form :inline="true" :model="reportProjectSearchForm">
            <el-form-item label="项目编号">
              <el-input v-model="reportProjectSearchForm.code" placeholder="请输入项目编号" clearable></el-input>
            </el-form-item>
            <el-form-item label="项目名称">
              <el-input v-model="reportProjectSearchForm.name" placeholder="请输入项目名称" clearable></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchReportProjects">
                <el-icon><Search /></el-icon>
                查询
              </el-button>
              <el-button @click="resetReportProjectSearch">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        
        <!-- 项目列表 -->
        <el-table
          v-loading="reportProjectLoading"
          :data="reportProjectList"
          border
          style="width: 100%"
          height="400px"
          @selection-change="handleReportProjectSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column type="index" width="60" label="序号" align="center" />
          <el-table-column prop="code" label="项目编号" min-width="120" align="center" show-overflow-tooltip />
          <el-table-column prop="name" label="项目名称" min-width="180" align="center" show-overflow-tooltip />
          <el-table-column prop="status" label="项目状态" min-width="100" align="center" show-overflow-tooltip />
          <el-table-column prop="customerName" label="客户名称" min-width="180" align="center" show-overflow-tooltip />
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="reportProjectPagination.page"
            v-model:page-size="reportProjectPagination.limit"
            :page-sizes="[10, 20, 50, 100]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="reportProjectPagination.total"
            @size-change="handleReportProjectSizeChange"
            @current-change="handleReportProjectPageChange"
          />
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reportProjectSelectorVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmReportProjectSelect" :disabled="!selectedReportProjectRow">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 打印预算单弹窗 -->
    <el-dialog
      v-model="budgetDialog.visible"
      :title="budgetDialog.title"
      :width="budgetDialog.width"
      :before-close="handleCloseBudgetDialog">
      <BudgetSheetPreview 
        :budget-data="currentBudgetSheet" 
        :warranty-period-year-options="warrantyPeriodYearOptions"
        :delivery-payment-details="deliveryPaymentDetails"
        :installation-payment-details="installationPaymentDetails"
        ref="budgetPreviewRef">
        <template #footer>
          <div class="print-area">
            <el-button type="primary" @click="printBudgetSheet" class="print-button">打印预算单</el-button>
          </div>
        </template>
      </BudgetSheetPreview>
      
      <template #footer>
        <el-button @click="handleCloseBudgetDialog">取消</el-button>
        <el-button type="primary" @click="printBudgetSheet">打印</el-button>
        <el-button type="success" @click="saveBudgetSheet">保存</el-button>
      </template>
    </el-dialog>
    
    <!-- 产品预算明细成本报表弹窗 -->
    <el-dialog
      v-model="budgetDetailReportDialog.visible"
      :title="budgetDetailReportDialog.title"
      :width="budgetDetailReportDialog.width"
      :before-close="handleCloseBudgetDetailReportDialog">
      <BudgetDetailReportPreview 
        :report-data="currentBudgetDetailReport"
        ref="budgetDetailReportPreviewRef">
      
      </BudgetDetailReportPreview>
      
      <template #footer>
        <el-button @click="handleCloseBudgetDetailReportDialog">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getBudgetSheetListApi, deleteBudgetSheetApi, getBudgetSheetDetailAllApi, saveHistoricalBudgetSheetApi, getBudgetDetailReportApi } from '@/api/budgetSheet/index'
import type { BudgetSheet, BudgetSheetQuery, BudgetDetailReport, BudgetDetailReportQuery } from '@/api/budgetSheet/type'
import { Search, Refresh, Plus, Document } from '@element-plus/icons-vue'
import ArchiveSelector from "@/components/common/ArchiveSelector.vue"
import BudgetSheetPreview from '@/components/budgetSheet/BudgetSheetPreview.vue'
import BudgetDetailReportPreview from '@/components/budgetSheet/BudgetDetailReportPreview.vue'
import { getSimpleProject } from '@/api/project'
import { ProjectDocument, ProjectDocumentListParam } from '@/api/project/type'
import { getSimpleCustomer } from '@/api/companyCustomer'
import { getSimpleUser } from '@/api/user'
import SysDialog from '@/components/dialog/SysDialog.vue'
import useDialog from '@/hooks/useDialog'
import { formatPrice, formatPercentage } from '@/utils/formatter'
import { handleError } from '@/utils/errorHandler'
import { getListApi as getDictListApi } from '@/api/sysDictData'
import { getProjectDocumentListApi } from "@/api/project";

// @ts-nocheck

// 遮罩层
const loading = ref(true)
// 总条数
const total = ref(0)
// 预算单表格数据
const dataList = ref<BudgetSheet[]>([])
// 表格高度自适应
const tableHeight = ref(0)

// 项目选项
const projectOptions = ref<any[]>([])
// 客户选项
const customerOptions = ref<any[]>([])
// 业务员选项
const personOptions = ref<any[]>([])

// 查询参数
const queryParams = reactive<BudgetSheetQuery>({
  page: 1,
  limit: 10,
  projectId: undefined,
  customerId: undefined,
  personId: undefined
})

// 项目选择器相关
const projectSelectorVisible = ref(false)
const reportProjectSelectorVisible = ref(false)
const selectedProject = ref<any>(null)
const selectedReportProject = ref<any>(null)
const projectSearchFields = [
  { label: '项目编号', prop: 'code', type: 'input' as const },
  { label: '项目名称', prop: 'name', type: 'input' as const }
]
const projectTableColumns = [
  { label: '项目编号', prop: 'code' },
  { label: '项目名称', prop: 'name' },
  { label: '项目状态', prop: 'status' }
]

// 报表项目选择器相关
const reportProjectSearchForm = reactive({
  code: '',
  name: '',
  page: 1,
  limit: 10
})
const reportProjectList = ref<any[]>([])
const reportProjectLoading = ref(false)
const reportProjectPagination = reactive({
  page: 1,
  limit: 10,
  total: 0
})
const selectedReportProjectRow = ref<any>(null)

// 打开项目选择器
const openProjectSelector = () => {
  projectSelectorVisible.value = true
}

// 打开报表项目选择器
const openProjectSelectorForReport = () => {
  reportProjectSelectorVisible.value = true
  // 重置选中的项目
  selectedReportProjectRow.value = null
  // 加载项目列表
  searchReportProjects()
}

// 查询报表项目列表
const searchReportProjects = async () => {
  reportProjectLoading.value = true
  try {
    const params: ProjectDocumentListParam = {
      code: reportProjectSearchForm.code,
      name: reportProjectSearchForm.name,
      customer: undefined,
      status: undefined,
      page: reportProjectPagination.page,
      limit: reportProjectPagination.limit
    }
    
    const res = await getProjectDocumentListApi(params)
    if (res.code === 200) {
      reportProjectList.value = res.data.list || []
      reportProjectPagination.total = res.data.total || 0
    } else {
      ElMessage.error(res.msg || '获取项目列表失败')
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
    ElMessage.error('获取项目列表失败')
  } finally {
    reportProjectLoading.value = false
  }
}

// 重置报表项目搜索条件
const resetReportProjectSearch = () => {
  reportProjectSearchForm.code = ''
  reportProjectSearchForm.name = ''
  reportProjectPagination.page = 1
  searchReportProjects()
}

// 处理报表项目表格选择变化
const handleReportProjectSelectionChange = (selection: any[]) => {
  selectedReportProjectRow.value = selection.length > 0 ? selection[0] : null
}

// 处理报表项目分页大小改变
const handleReportProjectSizeChange = (size: number) => {
  reportProjectPagination.limit = size
  searchReportProjects()
}

// 处理报表项目页码改变
const handleReportProjectPageChange = (page: number) => {
  reportProjectPagination.page = page
  searchReportProjects()
}

// 确认选择报表项目
const confirmReportProjectSelect = () => {
  if (!selectedReportProjectRow.value) {
    ElMessage.warning('请先勾选一个项目')
    return
  }
  
  selectedReportProject.value = selectedReportProjectRow.value
  console.log('选择的项目:', selectedReportProjectRow.value)
  ElMessage.info(`已选择项目: ${selectedReportProjectRow.value.name}`)
  
  // 关闭对话框
  reportProjectSelectorVisible.value = false
  
  // 生成报表
  handleGenerateBudgetDetailReport(selectedReportProjectRow.value.id)
}

// 打印预算单相关
const budgetDialog = reactive({
  visible: false,
  title: '',
  width: '900px'
})

// 预算明细成本报表弹窗
const budgetDetailReportDialog = reactive({
  visible: false,
  title: '',
  width: '1400px'
})

// 当前预算明细成本报表数据
const currentBudgetDetailReport = ref<BudgetDetailReport>({
  items: []
})

// 当前选中的预算单数据
const currentBudgetSheet = ref<BudgetSheet & {
  integratedPlanningType?: string;
  productCostExpenses?: number;
  productSalesAmount?: number;
  productPackagingExpenses?: number;
  productTransportExpenses?: number;
  shelfInstallationExpenses?: number;
  equipmentInstallationExpenses?: number;
  electricControlInstallationExpenses?: number;
  electricControlDebugExpenses?: number;
  softwareDebugExpenses?: number;
  projectManagementExpenses?: number;
  operationManagementExpenses?: number;
  warrantyPeriod?: number;
  otherExpenses?: number;
  marketingExpenses?: string;
  financialCost?: number;
  salesCommission?: number;
  total?: number;
  marketingExpensesPrice?: number;
  proportionReceivedPayment?: number;
  paymentCycle?: number;
  proportionReceivedPaymentAmount?: number;
  installationAcceptancePayment?: number;
  paymentCycle2?: number;
  installationAcceptancePaymentRatio?: number;
  warrantyCost?: number;
  warrantyPeriodMonth?: number;
  warrantyMoney?: number;
  acceptanceTime?: number | string;
  acceptanceMoney?: number | string;
  acceptanceMoneyCost?: number;
  salesCommissionAmount?: number;
  salesCommissionAmountRatio?: number;
  preSalesPlanningCommission?: number;
  preSalesPlanningCommissionRatio?: number;
  projectAnimationCommission?: number;
  projectAnimationCommissionRatio?: number;
  nonStandardColorFee?: number;
}>({})

// 付款信息详情数据
const deliveryPaymentDetails = ref<Array<{ratio: number, cycle: number}>>([])
const installationPaymentDetails = ref<Array<{ratio: number, cycle: number}>>([])

// 解析付款详情数据
const parsePaymentDetails = (budgetData: any) => {
  // 解析到货款详情
  if (budgetData.deliveryPaymentDetail) {
    try {
      const deliveryData = JSON.parse(budgetData.deliveryPaymentDetail)
      if (Array.isArray(deliveryData) && deliveryData.length > 0) {
        deliveryPaymentDetails.value = deliveryData
      }
    } catch (e) {
      // 如果解析失败，使用原有字段数据
      if (budgetData.proportionReceivedPaymentAmount || budgetData.paymentCycle) {
        deliveryPaymentDetails.value = [{
          ratio: budgetData.proportionReceivedPaymentAmount || 0,
          cycle: budgetData.paymentCycle || 0
        }]
      }
    }
  } else if (budgetData.proportionReceivedPaymentAmount || budgetData.paymentCycle) {
    // 如果没有详细数据但有原字段数据，转换为列表
    deliveryPaymentDetails.value = [{
      ratio: budgetData.proportionReceivedPaymentAmount || 0,
      cycle: budgetData.paymentCycle || 0
    }]
  }
  
  // 解析安装验收款详情
  if (budgetData.installationPaymentDetail) {
    try {
      const installationData = JSON.parse(budgetData.installationPaymentDetail)
      if (Array.isArray(installationData) && installationData.length > 0) {
        installationPaymentDetails.value = installationData
      }
    } catch (e) {
      // 如果解析失败，使用原有字段数据
      if (budgetData.installationAcceptancePaymentRatio || budgetData.paymentCycle2) {
        installationPaymentDetails.value = [{
          ratio: budgetData.installationAcceptancePaymentRatio || 0,
          cycle: budgetData.paymentCycle2 || 0
        }]
      }
    }
  } else if (budgetData.installationAcceptancePaymentRatio || budgetData.paymentCycle2) {
    // 如果没有详细数据但有原字段数据，转换为列表
    installationPaymentDetails.value = [{
      ratio: budgetData.installationAcceptancePaymentRatio || 0,
      cycle: budgetData.paymentCycle2 || 0
    }]
  }
}

// 路由实例
const router = useRouter()

// 使用dialog钩子获取弹窗控制方法
const { dialog, onShow, onClose } = useDialog()

// 获取项目列表 (为ArchiveSelector组件提供)
const getProjectList = async (params: any) => {
  try {
    // 构建查询参数
    const queryParams: ProjectDocumentListParam = {
      name: params.name,
      code: params.code,
      customer: params.customer,
      status: params.status,
      page: params.page || 1,
      limit: params.limit || 10
    };

    // 调用项目列表API - 使用真实API
    return await getProjectDocumentListApi(queryParams);
  } catch (error) {
    console.error('获取项目列表失败:', error);
    return {data: {list: [], total: 0}};
  }
};

// 处理项目选择确认
const handleProjectSelect = (project: ProjectDocument) => {
  selectedProject.value = project;
  console.log('选择的项目:', project);
  queryParams.projectId = project.id || 0;
};

// 处理报表项目选择
const handleReportProjectSelect = (selection: ProjectDocument[]) => {
  if (selection && selection.length > 0) {
    selectedReportProject.value = selection[0]
    console.log('选择的项目:', selection[0])
    ElMessage.info(`已选择项目: ${selection[0].name}`)
    handleGenerateBudgetDetailReport(selection[0].id)
  } else {
    console.log('未选择项目')
    ElMessage.warning('未选择项目')
  }
}

// 获取项目选项
const getProjectOptions = async () => {
  try {
    const res = await getSimpleProject()
    projectOptions.value = res.data|| []
  } catch (error) {
    console.error('获取项目列表失败', error)
  }
}

// 获取客户选项
const getCustomerOptions = async () => {
  try {
    const res = await getSimpleCustomer()
    customerOptions.value = res.data || []
  } catch (error) {
    console.error('获取客户列表失败', error)
  }
}

// 获取业务员选项
const getPersonOptions = async () => {
  try {
    const res = await getSimpleUser()
    personOptions.value = res.data || []
  } catch (error) {
    console.error('获取业务员列表失败', error)
  }
}

// 查询预算单列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getBudgetSheetListApi(queryParams)
    dataList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取预算单列表失败', error)
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  selectedProject.value = null
  queryParams.projectId = undefined
  queryParams.customerId = undefined
  queryParams.personId = undefined
  queryParams.page = 1
  getList()
}

// 新增按钮操作
const handleAdd = () => {
  router.push({ path: '/compute/budgetSheet/form' })
}

// 生成产品预算明细成本报表
const handleGenerateBudgetDetailReport = (projectId?: number) => {
  // 如果没有选择项目，显示提示
  if (!projectId && !selectedReportProject.value) {
    ElMessage.warning('请先选择项目')
    return
  }
  
  const finalProjectId = projectId || selectedReportProject.value?.id
  
  // 构建查询参数
  const reportParams: BudgetDetailReportQuery = {
    projectId: finalProjectId,
    customerId: undefined,
    personId: undefined
  }
  
  console.log('发送报表查询参数:', reportParams)
  
  // 显示加载状态
  loading.value = true
  
  // 调用API获取报表数据
  getBudgetDetailReportApi(reportParams)
    .then(res => {
      console.log('报表API响应:', res)
      if (res.code === 200) {
        if (!res.data || !res.data.items || res.data.items.length === 0) {
          ElMessage.warning('该项目没有预算明细数据')
          return
        }
        currentBudgetDetailReport.value = res.data
        budgetDetailReportDialog.visible = true
      } else {
        ElMessage.error(res.msg || '获取预算明细成本报表失败')
      }
    })
    .catch(error => {
      console.error('获取预算明细成本报表失败', error)
      ElMessage.error('获取预算明细成本报表失败: ' + (error.message || '未知错误'))
    })
    .finally(() => {
      loading.value = false
    })
}



// 查看按钮操作
const handleDetail = (id: number) => {
  router.push({ 
    path: `/compute/budgetSheet/form/${id}`,
    query: { display: 'true' }
  })
}

// 编辑按钮操作
const handleEdit = (id: number) => {
  router.push({ path: `/compute/budgetSheet/form/${id}` })
}

// 删除按钮操作
const handleDelete = (id: number) => {
  ElMessageBox.confirm('确认删除该预算单数据吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteBudgetSheetApi(id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除预算单失败', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 每页数量改变
const handleSizeChange = (size: number) => {
  queryParams.limit = size
  getList()
}

// 页码改变
const handleCurrentChange = (page: number) => {
  queryParams.page = page
  getList()
}

// 格式化日期
const formatDate = (date: string) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 处理打印按钮点击
const handlePrint = (row: BudgetSheet) => {
  if (!row.id) {
    ElMessage.error('预算单ID不存在，无法打印')
    return
  }
  
  getBudgetSheetDetailAllApi(row.id).then(res => {
    // @ts-ignore - 后端返回的数据结构可能与TypeScript定义不完全一致
    currentBudgetSheet.value = res.data
    // 解析付款详情数据
    parsePaymentDetails(res.data)
  })
  budgetDialog.visible = true
  budgetDialog.title = '预算单详情'
}

const budgetPreviewRef = ref<InstanceType<typeof BudgetSheetPreview> | null>(null)
const budgetDetailReportPreviewRef = ref<InstanceType<typeof BudgetDetailReportPreview> | null>(null)

// 打印预算单
const printBudgetSheet = () => {
  const printWindow = window.open('', 'PRINT', 'height=800,width=1200')
  if (printWindow) {
    // 获取预览组件的DOM元素
    const previewElement = document.querySelector('.budget-content')
    if (!previewElement) {
      ElMessage.error('获取预算单内容失败')
      return
    }
    
    const printContents = previewElement.innerHTML
    
    // 直接使用打印内容
    printWindow.document.write(`
      <html>
        <head>
          <title>预算单</title>
          <base href="${window.location.origin}${window.location.pathname}">
          <style>
            body { font-family: SimSun, serif; margin: 0; padding: 0; text-align: center; }
            table { width: 99%; border-collapse: collapse; margin: 0 auto; }
            table, th, td { border: 1px solid black; }
            th, td { padding: 5px; text-align: center; vertical-align: middle; }
            .header { display: flex; justify-content: space-between; align-items: center; padding: 10px 0; text-align: center; }
            .title { font-size: 18px; font-weight: bold; text-align: center; }
            .date { text-align: center; }
            .yellow-bg { background-color: #FFFF00; }
            .yellow-bg td { text-align: center; vertical-align: middle; }
            .pink-bg { background-color: #FFCCCC; }
            .blue-bg { background-color: #CCFFFF; }
            .total-row { font-weight: bold; }
            .print-button { display: none !important; }
            .budget-header { 
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 24px;
              padding-bottom: 16px;
              border-bottom: 1px solid #ebeef5;
              position: relative;
              text-align: center;
            }
            .budget-logo {
              position: absolute;
              top: 10px;
              text-align: center;
            }
            .budget-logo img.logo-image {
              max-width: 150px;
              height: auto;
              margin: 0 auto;
            }
            .budget-info {
              text-align: center;
              margin: 0 auto;
              width: 100%;
            }
            .budget-info h2 {
              margin: 0;
              font-size: 24px;
              color: #303133;
              text-align: center;
            }
            .budget-date {
              text-align: center;
              font-size: 14px;
              color: #606266;
            }
            .budget-table {
              width: 99%;
              border-collapse: collapse;
              margin: 16px auto;
            }
            .budget-table td {
              text-align: center;
              vertical-align: middle;
              padding: 8px;
              border: 1px solid #000;
            }
            .budget-footer {
              margin-top: 24px;
              padding-top: 16px;
              border-top: 1px solid #ebeef5;
              display: flex;
              justify-content: center;
              align-items: center;
              text-align: center;
            }
            .total-row td {
              font-weight: bold;
              background-color: #f2f2f2;
              text-align: center;
              vertical-align: middle;
            }
          </style>
        </head>
        <body>
          ${printContents}
        </body>
      </html>
    `)
    printWindow.document.close()
    printWindow.focus()
    printWindow.print()
    printWindow.close()
    budgetDialog.visible = false
  } else {
    ElMessage.error('无法打开打印窗口，请检查浏览器设置')
  }
}

// 关闭预算单弹窗
const handleCloseBudgetDialog = () => {
  budgetDialog.visible = false
}

// 打印预算明细成本报表
const printBudgetDetailReport = () => {
  const printWindow = window.open('', 'PRINT', 'height=800,width=1200')
  if (printWindow) {
    // 获取预览组件的DOM元素
    const previewElement = document.querySelector('.budget-detail-report')
    if (!previewElement) {
      ElMessage.error('获取预算明细成本报表内容失败')
      return
    }
    
    const printContents = previewElement.innerHTML
    
    // 直接使用打印内容
    printWindow.document.write(`
      <html>
        <head>
          <title>产品预算明细成本报表</title>
          <base href="${window.location.origin}${window.location.pathname}">
          <style>
            body { font-family: SimSun, serif; margin: 0; padding: 20px; }
            .budget-detail-header { margin-bottom: 24px; text-align: center; }
            .budget-detail-info h2 { margin: 0; font-size: 24px; text-align: center; }
            .budget-detail-date { text-align: center; font-size: 14px; margin-top: 8px; }
            table { width: 100%; border-collapse: collapse; margin: 16px 0; }
            table, th, td { border: 1px solid black; }
            th, td { padding: 8px; text-align: center; }
            .budget-detail-summary { text-align: right; margin-top: 20px; font-weight: bold; }
            .print-button { display: none !important; }
          </style>
        </head>
        <body>
          ${printContents}
        </body>
      </html>
    `)
    printWindow.document.close()
    printWindow.focus()
    printWindow.print()
    printWindow.close()
    budgetDetailReportDialog.visible = false
  } else {
    ElMessage.error('无法打开打印窗口，请检查浏览器设置')
  }
}

// 关闭预算明细成本报表弹窗
const handleCloseBudgetDetailReportDialog = () => {
  budgetDetailReportDialog.visible = false
}

// 保存预算单到历史记录
const saveBudgetSheet = () => {
  if (!currentBudgetSheet.value || !currentBudgetSheet.value.id) {
    ElMessage.warning('未获取到预算单数据，无法保存')
    return
  }
  
  // 获取预览组件的DOM元素
  const previewElement = document.querySelector('.budget-content')
  if (!previewElement) {
    ElMessage.error('获取预算单内容失败')
    return
  }
  
  // 构建完整的HTML内容，包含样式
  const styleContent = `
    <style>
      body { font-family: SimSun, serif; margin: 0; padding: 0; text-align: center; }
      table { width: 99%; border-collapse: collapse; margin: 0 auto; }
      table, th, td { border: 1px solid black; }
      th, td { padding: 5px; text-align: center; vertical-align: middle; }
      .header { display: flex; justify-content: space-between; align-items: center; padding: 10px 0; text-align: center; }
      .title { font-size: 18px; font-weight: bold; text-align: center; }
      .date { text-align: center; }
      .yellow-bg { background-color: #FFFF00; }
      .yellow-bg td { text-align: center; vertical-align: middle; }
      .pink-bg { background-color: #FFCCCC; }
      .blue-bg { background-color: #CCFFFF; }
      .total-row { font-weight: bold; }
      .print-button { display: none !important; }
      .budget-header { 
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 24px;
        padding-bottom: 16px;
        border-bottom: 1px solid #ebeef5;
        position: relative;
        text-align: center;
      }
      .budget-logo {
        position: absolute;
        top: 10px;
        text-align: center;
      }
      .budget-logo img.logo-image {
        max-width: 150px;
        height: auto;
        margin: 0 auto;
      }
      .budget-info {
        text-align: center;
        margin: 0 auto;
        width: 100%;
      }
      .budget-info h2 {
        margin: 0;
        font-size: 24px;
        color: #303133;
        text-align: center;
      }
      .budget-date {
        text-align: center;
        font-size: 14px;
        color: #606266;
      }
      .budget-table {
        width: 99%;
        border-collapse: collapse;
        margin: 16px auto;
      }
      .budget-table td {
        text-align: center;
        vertical-align: middle;
        padding: 8px;
        border: 1px solid #000;
      }
      .budget-footer {
        margin-top: 24px;
        padding-top: 16px;
        border-top: 1px solid #ebeef5;
        display: flex;
        justify-content: center;
        align-items: center;
        text-align: center;
      }
      .total-row td {
        font-weight: bold;
        background-color: #f2f2f2;
        text-align: center;
        vertical-align: middle;
      }
    </style>
  `
  
  // 获取内容并移除打印按钮
  let htmlContent = previewElement.innerHTML
  // 将打印按钮部分替换为空
  htmlContent = htmlContent.replace(/<div class="budget-footer">[\s\S]*?<\/div>/g, '')
  
  // 完整的HTML文档
  const fullContent = `
    <div class="budget-content">
      ${htmlContent}
    </div>
    ${styleContent}
  `
  
  // 构建保存数据
  const saveData = {
    budgetSheetId: currentBudgetSheet.value.id,
    projectId: currentBudgetSheet.value.projectId || 0,
    content: fullContent
  }
  
  // 调用保存API
  saveHistoricalBudgetSheetApi(saveData)
    .then((res) => {
      if (res.code === 200) {
        ElMessage.success('预算单保存成功')
        handleCloseBudgetDialog()
      } else {
        ElMessage.error(res.msg || '保存预算单失败')
      }
    })
    .catch((err) => {
      console.error('保存预算单失败', err)
      ElMessage.error('保存预算单失败')
    })
}

const warrantyPeriodYearOptions = ref<any[]>([])

const getWarrantyPeriodYearLabel = (value: string | number | undefined) => {
  const found = warrantyPeriodYearOptions.value.find(item => String(item.dictValue) === String(value))
  return found ? found.dictLabel : (value ?? '')
}

const getWarrantyPeriodYearOptions = async () => {
  try {
    const res = await getDictListApi({
      dictType: 'warrantyPeriodYear',
      dictLabel: '',
      status: undefined,
      page: 0,
      limit: 100
    })
    if (res && res.data) {
      warrantyPeriodYearOptions.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取类型列表失败:', error)
  }
}

onMounted(async () => {
  getProjectOptions()
  getCustomerOptions()
  getPersonOptions()
  getList()
  await getWarrantyPeriodYearOptions()
  
  // 设置表格高度
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    nextTick(() => {
      tableHeight.value = window.innerHeight - 260
    })
  })
})
</script>

<style lang="scss" scoped>
.container {
  background: #f5f7fa;
  padding: 20px;
  min-height: calc(100vh - 60px);
}

.search-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: none;
  margin-bottom: 20px;
  
  .search-wrapper {
    padding: 20px;
    display: flex;
    flex-direction: column;
    gap: 16px;
  }
  
  // 搜索表单区域
  .search-form-section {
    .demo-form-inline {
      display: flex;
      flex-wrap: wrap;
      gap: 16px;
      align-items: flex-end;
      
      .el-form-item {
        margin-bottom: 0;
        
        .el-input {
          border-radius: 8px;
          
          .el-input__wrapper {
            transition: all 0.3s ease;
            
            &:hover {
              box-shadow: 0 0 0 1px #409eff inset;
            }
          }
        }
        
        .el-select {
          .el-input__wrapper {
            border-radius: 8px;
            transition: all 0.3s ease;
            
            &:hover {
              box-shadow: 0 0 0 1px #409eff inset;
            }
          }
        }
        
        &.search-buttons {
          .el-button {
            margin-right: 8px;
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.3s ease;
            
            &:hover {
              transform: translateY(-1px);
              box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
            }
            
            &.search-btn {
              background: linear-gradient(135deg, #409EFF 0%, #1989fa 100%);
              border: none;
              color: white;
              
              &:hover {
                background: linear-gradient(135deg, #1989fa 0%, #409EFF 100%);
              }
            }
            
            &.reset-btn {
              background: linear-gradient(135deg, #F56C6C 0%, #F78989 100%);
              border: none;
              color: white;
              
              &:hover {
                background: linear-gradient(135deg, #F78989 0%, #F56C6C 100%);
              }
            }
          }
        }
      }
    }
  }
  
  // 操作按钮区域
  .action-buttons-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 16px;
    border-top: 1px solid #ebeef5;
    
    .button-group {
      display: flex;
      gap: 10px;
      
      .el-button {
        border-radius: 8px;
        font-weight: 500;
        transition: all 0.3s ease;
        
        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
        }
        
        &.add-btn {
          background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
          border: none;
          color: white;
          padding: 10px 20px;
          
          &:hover {
            background: linear-gradient(135deg, #85CE61 0%, #67C23A 100%);
          }
        }
      }
    }
  }
}

.list-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: none;
  
  :deep(.el-table) {
    border-radius: 8px;
    overflow: hidden;
    
    .el-table__header-wrapper {
      .el-table__header {
        th {
          background: #f8fafc;
          color: #606266;
          font-weight: 600;
          border-bottom: 1px solid #e4e7ed;
        }
      }
    }
    
    .el-table__body-wrapper {
      .el-table__body {
        tr:hover {
          background-color: #f8fafc;
        }
        
        td {
          border-bottom: 1px solid #ebeef5;
        }
      }
    }
    
    .el-button {
      border-radius: 6px;
      
      &.el-button--small {
        padding: 5px 12px;
      }
    }
  }
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  
  :deep(.el-pagination) {
    .el-pager li {
      border-radius: 6px;
    }
    
    .btn-prev,
    .btn-next {
      border-radius: 6px;
    }
  }
}

.price-value {
  color: #E6A23C;
  font-weight: 600;
}

.date-value {
  color: #909399;
}

/* 打印预算单弹窗 */
.print-content {
  padding: 20px;
}

/* 报表项目选择器样式 */
.project-selector-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
  
  .search-area {
    margin-bottom: 16px;
    
    .el-form {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      align-items: flex-end;
    }
  }
  
  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 16px;
  }
}
</style> 